var config = require("../../config");
var utils = require("../../utils/utils");
var async = require('async');
var path = require('path');
var fs = require('fs');
var log = console.log;
var navigator = './database/navigator.json';
var articles = './database/articles.json';
var cateslist = './database/cateslist.json';

exports.index = function (req, res) {
  var params = req.query, ms_arr=[];
  if (params.msid) {
    ms_arr = params.msid.split('_');
  } else {
    ms_arr[0] = 0;
  }
  
  async.parallel([
    function (cb) {
      var _navigator = JSON.parse(fs.readFileSync(navigator));
      cb(null, _navigator);
    },
    function (cb) {
      var _articles = JSON.parse(fs.readFileSync(articles));
      cb(null, _articles)
    }
  ], function (error, results) {
    var navigator = results[0],
      articles = results[1];

    res.render('index', {
      config: config,
      navigator: navigator,
      articles: articles,
      ms_arr: ms_arr.join('_')
    });
  });
}

exports.preview = function (req, res) {
  var cssid = req.query.id, allConfig;
  // 读取活动配置 .json
  fs.readFile(
    path.join(__dirname,'../../') + 'database/' + cssid + '_actconfig.json',
    { flag: 'r+', encoding: 'utf8' },
    function (err, data) {
      if(err) {
        console.error(err);
        return;
      }
      allConfig = JSON.parse(data);

      async.parallel([
        function (cb) {
          var _navigator = JSON.parse(fs.readFileSync(navigator));
          cb(null, _navigator);
        },
        function (cb) {
          var _articles = JSON.parse(fs.readFileSync(articles));
          cb(null, _articles)
        }
      ], function (error, results) {
        var navigator = results[0],
          articles = results[1];
        res.render('preview', {
          title : "活动预览",
          allConfig: allConfig,
          config: config,
          cssid: cssid
        });
      });
  });
  
}

exports.ms_normal = function (req, res) {
  var params = req.body, allConfig = params.allConfig, cssid = params.cssid;

  // 写入活动配置 .json
  fs.writeFile(
    path.join(__dirname, '../../') + '/database/' + cssid + '_actconfig.json',
    JSON.stringify(allConfig),
    { flag: 'w+', encoding: 'utf8' },
    function (err, data) {
      if(err) {
        console.error(err);
        return;
      }
      // 写入 css 预处理器: scss/less
      var css = JSON.stringify(allConfig[params.index].css);
      fs.writeFile(
        'public/act/' + cssid + '.scss',
        '@charset "utf-8";'+ css.substr(1, css.length-2),
        { flag: 'w+', encoding: 'utf8' },
        function (err, data) {
          if(err) {
            console.error(err);
            return;
          }
          log('wrote success!');
          res.send({
            'status': 'ok',
            'allConfig': allConfig
          });
      });
    });

}

exports.ms_flash = function (req, res) {
  var params = req.body, allConfig = params.allConfig, cssid = params.cssid;

  // 写入活动配置 .json
  fs.writeFile(
    path.join(__dirname, '../../') + 'database/' + cssid + '_actconfig.json',
    JSON.stringify(allConfig),
    { flag: 'w+', encoding: 'utf8' },
    function (err, data) {
      if(err) {
        console.error(err);
        return;
      }
      // 写入 css 预处理器: scss/less
      var css = JSON.stringify(allConfig[params.index].css);
      fs.writeFile(
        'public/act/' + cssid + '.scss',
        '@charset "utf-8";'+ css.substr(1, css.length-2),
        { flag: 'w+', encoding: 'utf8' },
        function (err, data) {
          if(err) {
            console.error(err);
            return;
          }
          res.send({
            'status': 'ok',
            'allConfig': allConfig
          });
          log('wrote success!');
      });
    });
}

exports.article = function (req, res) {
  var params = req.params, id = params.id, template = req.query.temp;
  async.parallel([
    function (cb) {
      var _navigator = JSON.parse(fs.readFileSync(navigator));
      cb(null, _navigator);
    },
    function (cb) {
      var _articles = JSON.parse(fs.readFileSync(articles));
      cb(null, _articles)
    }
  ], function (error, results) {
    var navigator = results[0],
      article = results[1][id];
    if (utils.agent(req, res)) {
      if (template) {
        res.render('demo/' + id + '/' + template, {
          config: config,
          navigator: navigator
        });
      } else {
        res.render('demo/' + id + '/' + template, {
          config: config,
          navigator: navigator
        });
      }
    } else {
      if (template) {
        res.render('demo/' + id + '/' + template, {
          config: config,
          navigator: navigator
        });
      } else {
        res.render('article', {
          config: config,
          navigator: navigator,
          article: article
        });
      }
    }
  });
}